package com.corpgovernment.organization.service;

import com.corpgovernment.api.applytrip.enums.ApplyTripEmployeeEnum;
import com.corpgovernment.api.applytrip.soa.request.ApplyTripPersonEffectRequest;
import com.corpgovernment.api.applytrip.soa.response.TripPersonEffectResponse;
import com.corpgovernment.api.costcenter.model.CostCenter;
import com.corpgovernment.api.costcenter.service.ICostCenterService;
import com.corpgovernment.api.organization.bo.GetPassengerResponseBO;
import com.corpgovernment.api.organization.bo.PassengerBO;
import com.corpgovernment.api.organization.enums.CardTypeEnum;
import com.corpgovernment.api.organization.model.bookingrelation.BookingRange;
import com.corpgovernment.api.organization.model.ffpinfo.GetFfBasicsInfoResponse;
import com.corpgovernment.api.organization.model.org.OrgConfigInfoVo;
import com.corpgovernment.api.organization.model.org.request.GetOrgConfigRequest;
import com.corpgovernment.api.organization.model.org.response.GetOrgConfigResponse;
import com.corpgovernment.api.organization.model.passenger.*;
import com.corpgovernment.api.organization.model.user.NameInfoBo;
import com.corpgovernment.api.organization.model.user.employee.NameInfoVo;
import com.corpgovernment.api.organization.soa.switchbo.GetPassengerByUidResponse;
import com.corpgovernment.api.organization.soa.switchbo.GetPassengerNameRequest;
import com.corpgovernment.api.organization.soa.switchbo.GetPassengerNameResponse;
import com.corpgovernment.api.organization.soa.switchbo.getPassengerByUidRequest;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseRequestVO.UserInfo;
import com.corpgovernment.common.base.BaseService;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.CardEnum;
import com.corpgovernment.common.utils.EncryptUtils;
import com.corpgovernment.common.utils.ObjectStringTrimUtils;
import com.corpgovernment.organization.Bo.GetPassengerNameBo;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.convert.PassengerConvert;
import com.corpgovernment.organization.dataloader.ApplyTripClientLoader;
import com.corpgovernment.organization.dataloader.db.MbFreshPassengerLoader;
import com.corpgovernment.organization.entity.db.*;
import com.corpgovernment.organization.enumm.CorpPayTypeEnum;
import com.corpgovernment.organization.enumm.DefaultBookRangeEnum;
import com.corpgovernment.organization.mapper.*;
import com.corpgovernment.organization.mapper.MbFreshPassengerMapper;
import com.corpgovernment.organization.mapper.MbOrgUserIdcardMapper;
import com.corpgovernment.organization.mapper.MbPassportWarnInfoMapper;
import com.corpgovernment.organization.mapper.MbFreshPassengerRelationMapper;
import com.corpgovernment.organization.mapper.MbOrgEmployeeMapper;
import com.corpgovernment.organization.mapper.MbOrgNonEmployeeMapper;
import com.corpgovernment.organization.model.DeletePassengerRequest;
import com.corpgovernment.organization.model.SavePassengerRequest;
import com.corpgovernment.organization.model.SavePassengerResponse;
import com.corpgovernment.organization.util.StrUtils;
import com.corpgovernment.organization.vo.GetPassengerResponseVO;
import com.corpgovernment.supplier.entity.db.SupplierCompany;
import com.corpgovernment.supplier.mapper.SupplierCompanyMapper;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.corpgovernment.common.enums.SystemType.zhongjin;

/**
 * PassengerService
 */
@Service
@Slf4j
public class PassengerService extends BaseService {
	@Autowired
	private ApplyTripClientLoader applyTripClientLoader;
	@Autowired
	private PassengerConvert passengerConvert;
	@Autowired
	private IOrganizationEmployeeService organizationEmployeeService;
	@Autowired
	private IOrganizationInfoService organizationInfoService;
	@Autowired
	private IOrgUserIdCardService orgUserIdCardService;
	@Autowired
	private IOrganizationNonEmployeeService organizationNonEmployeeService;
	@Autowired
	private ICostCenterService costCenterService;
	@Autowired
	private OrganizationApollo organizationApollo;
	@Autowired
	private BookingRelationService bookingRelationService;
	@Autowired
	private MbFreshPassengerLoader freshPassengerLoader;
	@Autowired
	private IOrgConfigService orgConfigService;
	@Autowired
	private MbOrgEmployeeMapper mbOrgEmployeeMapper;
	@Autowired
	private MbOrgNonEmployeeMapper mbOrgNonEmployeeMapper;
	@Autowired
	private IOrganizationNonEmployeeService organizationNonEmployeeInfoService;
	@Autowired
	private IFreshPassengerService freshPassengerService;
	@Autowired
    private MbPassportWarnInfoMapper mbPassportWarnInfoMapper;
	@Autowired
    private MbFreshPassengerRelationMapper mbFreshPassengerRelationMapper;

    @Autowired
    private MbFreshPassengerMapper mbFreshPassengerMapper;

    @Autowired
    private MbOrgUserIdcardMapper mbOrgUserIdcardMapper;

	@Resource
	private SupplierCompanyMapper mbSupplierCompanyMapper;

    private static final String ADD = "ADD";

    private static final String UPDATE = "UPDATE";

    private static final String VALID = "T";

    private static final String PATTERN = "yyyy-MM-dd";

    /**
	 * 获取可用出行人
	 *
	 * @param request
	 * @return
	 */
	public GetPassengerResponseVO getPassenger(GetPassengerRequest request) {
		try {
			initElkLog();
			addElkInfoLog("进入获取可用出行人流程");
			UserInfo userInfo = request.getUserInfo();
			String corpPayType = request.getCorpPayType();
			boolean isPub = Objects.equals(corpPayType, CorpPayTypeEnum.PUB.name());
			List<PassengerVo> passengerList;
			boolean showAdd = false;
			// 可代订的组织集合
			if (isPub) {
				addElkInfoLog("因公出行");
				// 出差申请单号
				String travelId = request.getTravelId();
				if (StringUtils.isNotBlank(travelId) && applyTripClientLoader.needVerifyPerson(travelId)) {
					addElkInfoLog("出差申请单模式");
					// 根据出差申请单获取出行人
					passengerList = this.getPassengerByTravel(request);
				} else {
					addElkInfoLog("无出差申请单模式或不管控人员");
					BookingRange bookingRange = bookingRelationService.queryBookingRangeByUidAndOrgId(userInfo.getUid(), userInfo.getOrgId());
					addElkInfoLog("该员工的代定范围：%s", JsonUtils.toJsonString(bookingRange));
					if (bookingRange != null) {
						showAdd = Optional.ofNullable(bookingRange.getBookForNonEmp()).orElse(false);
					}
					passengerList = this.getPassengerByPub(request, bookingRange);
				}
			} else {
				addElkInfoLog("因私出行");
				showAdd = true;
				passengerList = this.getPassengerByOwn(request);
			}
			String uid = userInfo.getUid();
			String orgId = userInfo.getOrgId();
			List<PassengerVo> subPassengerList = passengerList.stream().filter(e -> Objects.equals(e.getUid(), uid)).collect(Collectors.toList());
			passengerList.removeAll(subPassengerList);
			List<PassengerVo> passengerList2 = subPassengerList.stream().filter(e -> !Objects.equals(e.getOrgId(), orgId)).collect(Collectors.toList());
			passengerList.addAll(0, passengerList2);
			List<PassengerVo> finalPassengerList = passengerList;
			subPassengerList.stream().filter(e -> Objects.equals(e.getOrgId(), orgId)).findFirst().ifPresent(p -> {
				finalPassengerList.add(0, p);
			});
			//处理常用旅客
			passengerList = getPassengerRelationId(finalPassengerList, userInfo.getUid());
			return GetPassengerResponseVO.create(passengerList, showAdd);
		} finally {
			log.info("PassengerService.getPassenger获取可用出行人{} request：{}{}{}{}", System.lineSeparator(), JsonUtils.toJsonString(request), System.lineSeparator(), System.lineSeparator(), this.getElkInfoLog());
			clearElkLog();
		}

	}

	private List<PassengerVo> getPassengerRelationId(List<PassengerVo> passengerDtoList, String uid) {
		List<GetFfBasicsInfoResponse> data = organizationInfoService.getFfBasicsInfo(uid);
		log.info("查询出的常旅信息集合:{}", JsonUtils.toJsonString(data));
		if (CollectionUtils.isEmpty(data)) {
			return passengerDtoList;
		}

		Map<String, List<GetFfBasicsInfoResponse>> collect = data.stream().collect(Collectors.groupingBy(GetFfBasicsInfoResponse::getFreshUid));

		for (PassengerVo passengerVo : passengerDtoList) {
			List<GetFfBasicsInfoResponse> getFfBasicsInfoResponses = collect.get(passengerVo.getUid());
			if (CollectionUtils.isEmpty(getFfBasicsInfoResponses)) {
				continue;
			}
			passengerVo.setRelationFlag(Boolean.TRUE);
			passengerVo.setRelationId(getFfBasicsInfoResponses.get(0).getId());
		}

		return passengerDtoList;
	}


	/**
	 * 因私获取出行人
	 *
	 * @param requestVO
	 * @return
	 */
	private List<PassengerVo> getPassengerByOwn(GetPassengerRequest requestVO) {
		UserInfo userInfo = requestVO.getUserInfo();
		Integer pageNum = requestVO.getPage();
		String uid = userInfo.getUid();
		String orgId = userInfo.getOrgId();
		String query = requestVO.getQuery();
		List<MbFreshPassenger> freshPassengerList = new ArrayList<>();
		if (StringUtils.isBlank(query)) {
			freshPassengerList = freshPassengerLoader.pageByUidAndOrgId(uid, orgId, pageNum, CommonConst.PAGE_SIZE_30);
		} else {
			addElkInfoLog("查询条件：%s", query);
			String systemType = organizationApollo.getSystemType();
			List<Long> freshPassengerIds = new ArrayList<>();
			if (Objects.equals(zhongjin.getCode(), systemType)) {
				addElkInfoLog("名称精确匹配或身份证号精确匹配");
				// 名称精确匹配或身份证号精确匹配
				freshPassengerIds = this.queryByNameOrCardNo(query, false);
			} else {
				addElkInfoLog("名称模糊查询");
				// 名称模糊查询
				freshPassengerIds = this.queryLikeName(query, false);
			}
			if (CollectionUtils.isNotEmpty(freshPassengerIds)) {
				freshPassengerList = freshPassengerLoader.pageByUidAndOrgIdAndFreshPassengerIds(freshPassengerIds, uid, orgId, pageNum, CommonConst.PAGE_SIZE_30);
			}
		}
		if (CollectionUtils.isEmpty(freshPassengerList)) {
			return new ArrayList<>();
		}
		addElkInfoLog("出行人信息：%s", JsonUtils.toJsonString(freshPassengerList));
		List<PassengerVo> passengerList = passengerConvert.convertFromFreshPassenger(freshPassengerList, orgId);
		PageInfo<MbFreshPassenger> pageInfo = new PageInfo<>(freshPassengerList);
		int totalPage = pageInfo.getPages();
		boolean pageEnd = requestVO.getPage() == totalPage;
		// 3.完善出行人信息
		List<PassengerVo> result = this.packagePassengerList(passengerList, requestVO);
		result.forEach(e -> e.setPageEnd(pageEnd));
		if (CollectionUtils.isEmpty(result)) {
			addElkInfoLog("出行人为空，该日志不会存在");
			return new ArrayList<>();
		}
		List<PassengerInfo> selectedList = requestVO.getSelectedList();
		if (CollectionUtils.isEmpty(selectedList)) {
			return result;
		}
		// 将选中的员工排掉
		List<String> uidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getUid())).map(PassengerInfo::getUid).collect(Collectors.toList());
		List<String> noUidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).map(PassengerInfo::getNoEmployeeId).collect(Collectors.toList());
		return result.stream().filter(e -> !uidList.contains(e.getUid()) && !noUidList.contains(e.getNoEmployeeId())).collect(Collectors.toList());
	}

	/**
	 * 因公获取出行人
	 *
	 * @param requestVO
	 * @param bookingRange
	 * @return
	 */
	private List<PassengerVo> getPassengerByPub(GetPassengerRequest requestVO, BookingRange bookingRange) {
		List<String> bookingOrgIds = new ArrayList<>();
		List<BookingRange.BookingUser> bookingUsers = new ArrayList<>();
		boolean bookForNonEmp = false;
		String bookRangeCode = organizationApollo.getDefaultBookRange();
		addElkInfoLog("系统默认的代订范围：%s", bookRangeCode);
		DefaultBookRangeEnum bookRangeEnum = DefaultBookRangeEnum.getByCode(bookRangeCode);
		boolean isBooking = false;
		if (bookRangeEnum == DefaultBookRangeEnum.All) {
			isBooking = true;
			bookingOrgIds.addAll(organizationInfoService.listAllValidOrgId());
		} else {
			if (bookingRange != null) {
				isBooking = true;
				addElkInfoLog("该员工的代定范围：%s", JsonUtils.toJsonString(bookingRange));
				bookingOrgIds.addAll(bookingRange.getBookingRange());
				bookForNonEmp = bookingRange.getBookForNonEmp();
				bookingUsers = bookingRange.getBookingUsers();
			}
		}
		UserInfo userInfo = requestVO.getUserInfo();
		bookingOrgIds = bookingOrgIds.stream().distinct().collect(Collectors.toList());
		String query = requestVO.getQuery();
		String uid = userInfo.getUid();
		String orgId = userInfo.getOrgId();
		Integer page = requestVO.getPage();
		List<MbFreshPassenger> freshPassengerList = new ArrayList<>();
		if (bookForNonEmp) {
			addElkInfoLog("查询范围包括非员工");
			if (StringUtils.isBlank(query)) {
				freshPassengerList = freshPassengerLoader.pageByBookingOrgIds(bookingOrgIds, bookingUsers, uid, orgId, page, CommonConst.PAGE_SIZE_30);
			} else {
				addElkInfoLog("查询条件：%s", query);
				String systemType = organizationApollo.getSystemType();
				addElkInfoLog("系统模式：%s", systemType);
				List<Long> freshPassengerIds = new ArrayList<>();
				if (Objects.equals(zhongjin.getCode(), systemType)) {
					// 名称精确匹配或身份证号精确匹配
					freshPassengerIds = this.queryByNameOrCardNo(query, false);
				} else {
					// 名称模糊查询
					freshPassengerIds = this.queryLikeName(query, false);
				}
				addElkInfoLog("查询到的fresh id：%s", freshPassengerIds);
				if (CollectionUtils.isNotEmpty(freshPassengerIds)) {
					freshPassengerList = freshPassengerLoader.pageByBookingOrgIdsAndFreshPassengerIds(bookingOrgIds, bookingUsers, freshPassengerIds, uid, orgId, page, CommonConst.PAGE_SIZE_30);
				}
			}
		} else {
			addElkInfoLog("查询范围不包括非员工");
			String queryUid = requestVO.getUid();
			if (StringUtils.isBlank(query)) {
				addElkInfoLog("查询条件：%s", query);
				freshPassengerList = freshPassengerLoader.pageEmployeeByBookingOrgIds(bookingOrgIds, bookingUsers, queryUid, page, CommonConst.PAGE_SIZE_30, orgId);
			} else {
				String systemType = organizationApollo.getSystemType();
				addElkInfoLog("查询模式：%s", systemType);
				List<Long> freshPassengerIds = new ArrayList<>();
				if (Objects.equals(zhongjin.getCode(), systemType)) {
					// 名称精确匹配或身份证号精确匹配
					freshPassengerIds.addAll(this.queryByNameOrCardNo(query, true));
				} else {
					// 名称模糊查询
					freshPassengerIds.addAll(this.queryLikeName(query, true));
				}
				addElkInfoLog("查询到的fresh id：%s", freshPassengerIds);
				if (CollectionUtils.isNotEmpty(freshPassengerIds)) {
					freshPassengerList = freshPassengerLoader.pageEmployeeByBookingOrgIdsAndName(bookingOrgIds, bookingUsers, freshPassengerIds, queryUid, page, CommonConst.PAGE_SIZE_30, orgId);
				}
			}
		}
		addElkInfoLog("出行人信息：%s", JsonUtils.toJsonString(freshPassengerList));
		if (CollectionUtils.isEmpty(freshPassengerList)) {
			addElkInfoLog("未查到出行人，流程结束");
			return new ArrayList<>();
		}
		freshPassengerList = filterPassenger(freshPassengerList);
		PageInfo<MbFreshPassenger> pageInfo = new PageInfo<>(freshPassengerList);
		int totalPage = pageInfo.getPages();
		boolean pageEnd = requestVO.getPage() == totalPage;
		List<PassengerVo> passengerList = passengerConvert.convertFromFreshPassenger(freshPassengerList, orgId);
		// 3.完善出行人信息
		List<PassengerVo> result = this.packagePassengerList(passengerList, requestVO);
		result.forEach(e -> e.setPageEnd(pageEnd));
		if (CollectionUtils.isEmpty(result)) {
			return new ArrayList<>();
		}
		List<PassengerInfo> selectedList = requestVO.getSelectedList();
		if (CollectionUtils.isEmpty(selectedList)) {
			return result;
		}
		// 将选中的员工排掉
		List<String> uidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getUid())).map(PassengerInfo::getUid).collect(Collectors.toList());
		List<String> noUidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).map(PassengerInfo::getNoEmployeeId).collect(Collectors.toList());
		if (Objects.isNull(requestVO.getIsExcludeSelected()) || !requestVO.getIsExcludeSelected()) {
			return result.stream().filter(e -> !uidList.contains(e.getUid()) && !noUidList.contains(e.getNoEmployeeId())).collect(Collectors.toList());
		}
		return result.stream().filter(e -> {
			if (StringUtils.isEmpty(e.getUid())) {
				return noUidList.contains(e.getNoEmployeeId());
			} else {
				return uidList.contains(e.getUid());
			}
		}).collect(Collectors.toList());
	}

	public static void main(String[] args) {
		System.out.println(EncryptUtils.sm4Decrypt("Hbb6kDcc6LlHYa1SShvSKA=="));
	}

	private List<MbFreshPassenger> filterPassenger(List<MbFreshPassenger> freshPassengerList) {
		List<MbFreshPassenger> list = new ArrayList<>();
		Set<String> set = new HashSet<>();
		freshPassengerList.forEach(e -> {
			String key;
			if (StringUtils.isBlank(e.getEmployeeUid())) {
				key = e.getNonEmployeeUid() + "_" + e.getOrgId();
			} else {
				key = e.getEmployeeUid() + "_" + e.getOrgId();
			}
			if (set.contains(key)) {
				return;
			}
			list.add(e);
			set.add(key);
		});
		return list;
	}

	/**
	 * 根据名称模糊查询
	 *
	 * @param name         模糊查询条件
	 * @param needEmployee 是否必须为员工
	 * @return
	 */
	private List<Long> queryLikeName(String name, boolean needEmployee) {
		return freshPassengerLoader.queryLikeName(name, needEmployee);
	}

	/**
	 * 根据名称或证件精确匹配
	 *
	 * @param query        精确查询条件
	 * @param needEmployee 是否必须为员工
	 * @return
	 */
	private List<Long> queryByNameOrCardNo(String query, boolean needEmployee) {
		List<MbOrgUserIdcard> cardList = orgUserIdCardService.findByTypeAndNo(CardTypeEnum.ID_CARD.getCode(), query);
		if (CollectionUtils.isNotEmpty(cardList)) {
			List<Long> nonEmployeeIds = cardList.stream().map(MbOrgUserIdcard::getNonEmployeeId).filter(Objects::nonNull).collect(Collectors.toList());
			List<String> employeeIds = cardList.stream().map(MbOrgUserIdcard::getEmployeeUid).filter(org.apache.commons.lang.StringUtils::isNotBlank).collect(Collectors.toList());
			List<MbFreshPassenger> employeeList = new ArrayList<>();
			if (!needEmployee && CollectionUtils.isNotEmpty(nonEmployeeIds)) {
				employeeList.addAll(freshPassengerLoader.findByNonEmployeeIds(nonEmployeeIds));
			}
			if (CollectionUtils.isNotEmpty(employeeIds)) {
				employeeList.addAll(freshPassengerLoader.findByEmployeeIds(employeeIds));
			}
			return employeeList.stream().map(MbFreshPassenger::getId).collect(Collectors.toList());
		} else {
			return freshPassengerLoader.queryByName(query, needEmployee);
		}
	}

	/**
	 * 根据出差申请单获取出行人
	 *
	 * @param requestVO
	 * @return
	 */
	private List<PassengerVo> getPassengerByTravel(GetPassengerRequest requestVO) {
		// 1.调用出差申请的soa接口可用的出行人
		UserInfo userInfo = requestVO.getUserInfo();
		String site = requestVO.getSite();
		Integer returnType = requestVO.getReturnType();
		ApplyTripPersonEffectRequest request = new ApplyTripPersonEffectRequest();
		request.setApplyNo(requestVO.getTravelId());
		request.setTrafficId(requestVO.getTripId());
		request.setStartCityCode(requestVO.getDcity());
		request.setEndCityCode(requestVO.getAcity());
		request.setReturnType(returnType);
		request.setUid(userInfo.getUid());
		request.setOrgId(userInfo.getOrgId());
		request.setStartDate(requestVO.getStartDate());
		request.setEndDate(requestVO.getEndDate());
		request.setReturnType(requestVO.getReturnType());
		request.setStartCityName(requestVO.getDepartCityName());
		request.setEndCityName(requestVO.getArrivalCityName());
		request.setTrafficType(site);
		List<TripPersonEffectResponse> personList = applyTripClientLoader.listEffectTripPerson(request);
		if (CollectionUtils.isEmpty(personList)) {
			addElkInfoLog("出差申请单中没有可用的出行人");
			throw new CorpBusinessException(OrganizationResponseCodeEnum.APPLY_DONT_PASSENGER);
		}
		// 2.获取出差申请单中的出行人
		List<PassengerVo> passengerList = passengerConvert.convertFromTripPerson(personList);
		addElkInfoLog("获取出差申请单中的出行人：%s", JsonUtils.toJsonString(passengerList));
		// 3.完善出行人信息
		List<PassengerVo> result = this.packagePassengerList(passengerList, requestVO);
		addElkInfoLog("完善出行人信息：%", JsonUtils.toJsonString(result));
		if (CollectionUtils.isEmpty(result)) {
			return new ArrayList<>();
		}
		List<PassengerInfo> selectedList = requestVO.getSelectedList();
		addElkInfoLog("选中集合：%", JsonUtils.toJsonString(selectedList));
		if (CollectionUtils.isEmpty(selectedList)) {
			return result;
		}
		// 将选中的员工排掉
		List<String> uidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getUid())).map(PassengerInfo::getUid).collect(Collectors.toList());
		List<String> noUidList = selectedList.stream().filter(p -> StringUtils.isNotBlank(p.getNoEmployeeId())).map(PassengerInfo::getNoEmployeeId).collect(Collectors.toList());

		return result.stream().filter(e -> !uidList.contains(e.getUid()) && !noUidList.contains(e.getNoEmployeeId())).collect(Collectors.toList());
	}

	/**
	 * 获取员工信息
	 *
	 * @param passengerList
	 * @param request
	 * @return
	 */
	private List<PassengerVo> packagePassengerList(List<PassengerVo> passengerList, GetPassengerRequest request) {
		if (CollectionUtils.isEmpty(passengerList)) {
			addElkInfoLog("出行人为空，该日志不会存在");
			return new ArrayList<>();
		}
		String site = request.getSite();
		List<String> uids = passengerList.stream().map(PassengerVo::getUid).filter(Objects::nonNull).distinct().collect(Collectors.toList());
		List<String> orgIds = passengerList.stream().map(PassengerVo::getOrgId).distinct().collect(Collectors.toList());
		addElkInfoLog("出行人组织id集合：%s", JsonUtils.toJsonString(orgIds));
		List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
		Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
		addElkInfoLog("出行人组织集合：%s", JsonUtils.toJsonString(orgInfoMap));
		List<PassengerVo> result = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(uids)) {
			List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listByUids(uids);
			Map<String, MbOrgEmployeeInfo> employeeMap = employeeInfoList.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, Function.identity(), (e1, e2) -> e1));
			List<MbOrgUserIdcard> userIdCards = orgUserIdCardService.batchFindByUids(uids);
			Map<String, List<MbOrgUserIdcard>> uidCardMap = userIdCards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
			Map<String, CostCenter> costMap = Maps.newHashMap();
			List<PassengerVo> employeeList = passengerList.stream().filter(e->StringUtils.isNotBlank(e.getUid()) && Objects.nonNull(employeeMap.get(e.getUid()))).map(e->{
				String orgId = e.getOrgId();
				String uid = e.getUid();
				MbOrgInfo orgInfo = orgInfoMap.get(orgId);
				List<MbOrgUserIdcard> cardList = uidCardMap.get(uid);
				MbOrgEmployeeInfo employeeInfo = employeeMap.get(uid);
				PassengerVo passenger = passengerConvert.convertFromEmployee(employeeInfo, orgInfo, cardList, site);
				passenger.setId(e.getId());
				CostCenter costCenter = costMap.get(orgId);
				if (costCenter == null) {
					List<CostCenter> costCenters = costCenterService.getCostCenter(orgId);
					if (CollectionUtils.isNotEmpty(costCenters)){
						costMap.putIfAbsent(orgId, costCenters.get(0));
					}
				}
				passenger.setCostCenter(costCenter);
				passenger.setProjectCode(e.getProjectCode());
				passenger.setProjectName(e.getProjectName());
				passenger.setNoSelectProjectDesc(e.getNoSelectProjectDesc());
				return passenger;
			}).collect(Collectors.toList());
			addElkInfoLog("员工集合：%s", JsonUtils.toJsonString(employeeList));
			result.addAll(employeeList);
		}

		List<Long> nonEmployeeUids = passengerList.stream().map(PassengerVo::getNoEmployeeId).filter(Objects::nonNull).map(Long::valueOf).collect(Collectors.toList());
		addElkInfoLog("非员工id集合：%s", JsonUtils.toJsonString(nonEmployeeUids));
		if (CollectionUtils.isNotEmpty(nonEmployeeUids)) {
			List<MbOrgNonEmployeeInfo> nonEmployeeInfoList = organizationNonEmployeeService.listByIds(nonEmployeeUids);
			Map<Long, MbOrgNonEmployeeInfo> nonEmployeeMap = nonEmployeeInfoList.stream().collect(Collectors.toMap(MbOrgNonEmployeeInfo::getId, e -> e));
			List<MbOrgUserIdcard> userIdCards = orgUserIdCardService.batchFindByNonEmployeeUids(nonEmployeeUids);
			Map<Long, List<MbOrgUserIdcard>> uidCardMap = userIdCards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getNonEmployeeId));
			List<PassengerVo> nonEmployeeList = passengerList.stream().filter(e->StringUtils.isNotBlank(e.getNoEmployeeId())).map(e -> {
				Long nonEmployeeId = Long.valueOf(e.getNoEmployeeId());
				List<MbOrgUserIdcard> cardList = uidCardMap.get(nonEmployeeId);
				MbOrgNonEmployeeInfo nonEmployeeInfo = nonEmployeeMap.get(nonEmployeeId);
				PassengerVo passenger = passengerConvert.convertFromNonEmployee(nonEmployeeInfo, cardList, site);
				passenger.setId(e.getId());
				passenger.setCostCenter(e.getCostCenter());
				passenger.setProjectCode(e.getProjectCode());
				passenger.setProjectName(e.getProjectName());
				passenger.setNoSelectProjectDesc(e.getNoSelectProjectDesc());
				return passenger;
			}).collect(Collectors.toList());
			addElkInfoLog("非员工集合：%s", JsonUtils.toJsonString(nonEmployeeList));
			result.addAll(nonEmployeeList);
		}

		return result;
	}


	public List<GetPassengerByUidResponse> getPassengerByUid(getPassengerByUidRequest request) {
		List<GetPassengerByUidResponse> responses = Lists.newArrayList();
		List<MbOrgEmployeeInfo> employeeInfos = organizationEmployeeService.listByUidsAllPlat(request.getUids());
		employeeInfos.stream().forEach(mbOrgEmployeeInfo -> {responses.add(new GetPassengerByUidResponse(mbOrgEmployeeInfo.getUid(), mbOrgEmployeeInfo.getMobilePhone(), mbOrgEmployeeInfo.getNationality()));});
		return responses;
	}

	public GetPassengerResponseBO getValidPassengerSoa(GetPassengerRequest request) {
		GetPassengerResponseVO passenger = this.getPassenger(request);
		List<PassengerBO> passengerList = passengerConvert.convertFromVO(passenger.getPlist());
		return GetPassengerResponseBO.create(passengerList, passenger.getShowAdd());
	}

	public boolean getNameEditDuringBooking(String orgId){
		GetOrgConfigRequest getOrgConfigRequest = new GetOrgConfigRequest();
		getOrgConfigRequest.setOrgId(orgId);
		GetOrgConfigResponse orgConfig = orgConfigService.getOrgConfig(getOrgConfigRequest);
		return Optional.ofNullable(orgConfig.getOrgConfigInfo()).map(OrgConfigInfoVo::getNameEditDuringBooking).orElse(false);
	}

	public List<GetPassengerNameResponse> getPassengerName(List<GetPassengerNameRequest> request) {
		log.info("当前请求的request为:{}", JsonUtils.toJsonString(request));
		//参数校验，id和employeeType不能为空
		AtomicBoolean parameterValid = new AtomicBoolean(true);
		request.forEach(e ->{
			if (!verifyParam(e)){
				parameterValid.set(false);
			}
		});
		if (!parameterValid.get()){
			throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_TYPE_OR_ID_IS_NULL);
		}

		//过滤员工
		List<GetPassengerNameRequest> employeeList = request.stream().filter(e ->
				ApplyTripEmployeeEnum.EMPLOYEE.getCode().equals(e.getEmployeeType()) || ApplyTripEmployeeEnum.INFORMAL_EMPLOYEE.getCode().equals(e.getEmployeeType())
		).collect(Collectors.toList());
		Map<String, List<GetPassengerNameRequest>> employeeMap = listToMapById(employeeList);

		//过滤非员工
		List<GetPassengerNameRequest> nonEmployeeList = request.stream().filter(e ->
				ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode().equals(e.getEmployeeType())
		).collect(Collectors.toList());
		Map<String, List<GetPassengerNameRequest>> nonEmployeeMap = listToMapById(nonEmployeeList);

		ArrayList<GetPassengerNameResponse> result = new ArrayList<>();

		//查询员工
		List<String> employeeIdList = employeeList.stream().map(GetPassengerNameRequest::getId).collect(Collectors.toList());
		List<MbOrgEmployeeInfo> mbOrgEmployeeInfoList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(employeeIdList)) {
			Example example = new Example(MbOrgEmployeeInfo.class);
			example.createCriteria().andIn("uid", employeeIdList);
			mbOrgEmployeeInfoList = mbOrgEmployeeMapper.selectByExample(example);
		}
		log.info("查询出的员工信息集合为:{}", JsonUtils.toJsonString(mbOrgEmployeeInfoList));
		mbOrgEmployeeInfoList.forEach(e ->{
			employeeMap.get(e.getUid()).forEach(k -> {
				GetPassengerNameResponse response = new GetPassengerNameResponse();
				response.setId(e.getUid());
				response.setEmployeeType(e.getEmployeeType());
				response.setPassengerName(getPassengerName(new GetPassengerNameBo(e.getNameInfo(), e.getName(), e.getFirstEnName(), e.getLastEnName(), k)));
				response.setCardType(k.getCardType());
				result.add(response);
			});
		});

		//查询非员工
		List<Long> nonEmployeeIdList = nonEmployeeList.stream().map(GetPassengerNameRequest::getId).map(Long::parseLong).collect(Collectors.toList());
		List<MbOrgNonEmployeeInfo> mbOrgNonEmployeeInfoList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(nonEmployeeIdList)) {
			Example nonEmployeeExample = new Example(MbOrgNonEmployeeInfo.class);
			nonEmployeeExample.createCriteria().andIn("id", nonEmployeeIdList);
			mbOrgNonEmployeeInfoList = mbOrgNonEmployeeMapper.selectByExample(nonEmployeeExample);
		}
        log.info("查询出的非员工信息集合为:{}", JsonUtils.toJsonString(mbOrgEmployeeInfoList));
		mbOrgNonEmployeeInfoList.forEach(e ->{
			nonEmployeeMap.get(e.getId().toString()).forEach(k ->{
				GetPassengerNameResponse response = new GetPassengerNameResponse();
				response.setId(e.getId().toString());
				response.setEmployeeType(e.getEmployeeType());
				response.setPassengerName(getPassengerName(new GetPassengerNameBo(e.getNameInfo(), e.getName(), e.getFirstEnName(), e.getLastEnName(), k)));
				response.setCardType(k.getCardType());
				result.add(response);
			});

		});

		return result;
	}

	private Map<String, List<GetPassengerNameRequest>> listToMapById(List<GetPassengerNameRequest> list) {
		Map<String, List<GetPassengerNameRequest>> res = new HashMap<>();
		list.forEach(e ->{
			if (res.containsKey(e.getId())){
				res.get(e.getId()).add(e);
			} else {
				ArrayList<GetPassengerNameRequest> nameRequestList = new ArrayList<>();
				nameRequestList.add(e);
				res.put(e.getId(), nameRequestList);
			}
		});
		return res;
	}

	private boolean verifyParam(GetPassengerNameRequest request){
		if (Objects.isNull(request.getId()) || Objects.isNull(request.getEmployeeType())){
			return false;
		}
		if ("".equals(request.getId())){
			return false;
		}
		return ApplyTripEmployeeEnum.EMPLOYEE.getCode().equals(request.getEmployeeType()) || ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode().equals(request.getEmployeeType()) || ApplyTripEmployeeEnum.INFORMAL_EMPLOYEE.getCode().equals(request.getEmployeeType());
	}

	private String getPassengerName(GetPassengerNameBo passengerNameBo){
		String nameInfo = passengerNameBo.getNameInfo();
		// 是否读取nameInfo的数据,T:读取  F:不读取
		boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
		if(!nameInfoReadSwitch){
			nameInfo = null;
		}
		NameInfoVo nameInfoVo = null;
		try {
			nameInfoVo = JsonUtils.parse(nameInfo, NameInfoVo.class);
		}catch (Exception e){
			log.error("NameInfo JSON转换失败!");
		}

		//返回中文名
		if (needCnName(passengerNameBo.getRequest(), nameInfo)){
			return Optional.ofNullable(nameInfoVo).map(NameInfoVo::getFullName).orElse(passengerNameBo.getName());
		}
		//返回英文名
		if (Objects.isNull(nameInfoVo)){
			String firstEnName = passengerNameBo.getFirstEnName();
			String lastEnName = passengerNameBo.getLastEnName();
			if (StringUtils.isBlank(firstEnName) || StringUtils.isBlank(lastEnName)){
				throw new CorpBusinessException(OrganizationResponseCodeEnum.ENGLISH_NAME_INCOMPLETE);
			}
			return lastEnName + "/" + firstEnName;
		}
		String givenname = nameInfoVo.getGivenname();
		String surname = nameInfoVo.getSurname();
		if (StringUtils.isBlank(givenname) || StringUtils.isBlank(surname)){
			throw new CorpBusinessException(OrganizationResponseCodeEnum.ENGLISH_NAME_INCOMPLETE);
		}
		return surname + "/" + givenname;
	}

	private boolean needCnName(GetPassengerNameRequest request, String nameInfo){
		NameInfoVo nameInfoVo = null;
		try {
			nameInfoVo = JsonUtils.parse(nameInfo, NameInfoVo.class);
		}catch (Exception e){
			log.error("NameInfo JSON转换失败!");
		}
		if (StringUtils.isBlank(request.getLanguage())){
			if (Objects.isNull(request.getCardType())){
				return Objects.isNull(nameInfoVo) || StringUtils.isBlank(nameInfoVo.getNationality()) || startsWith(nameInfoVo.getNationality(), "CN", true);
			}else{
			    return CardEnum.needCnNameCardType(request.getCardType().toString());
			}
		}
		return "zh".equals(request.getLanguage());
	}

	private static boolean startsWith(String str, String prefix, boolean ignoreCase) {
		if (str != null && prefix != null) {
			return prefix.length() <= str.length() && str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());
		} else {
			return str == null && prefix == null;
		}
	}

	public SavePassengerResponse savePassenger(SavePassengerRequest request){
        ObjectStringTrimUtils.allFieldRemoveWarp(request);

        if (Objects.isNull(request.getRelationFlag())){
	        request.setRelationFlag(true);
        }
        CardVo cardVo = request.getCard();
        if (Objects.nonNull(cardVo)){
            if (CardEnum.needUpperCaseCard(cardVo.getType().toString())){
                cardVo.setValue(cardVo.getValue().toUpperCase());
            }
        }

		// 1.保存新建的非员工
		MbOrgNonEmployeeInfo nonEmployeeInfo = new MbOrgNonEmployeeInfo();
		nonEmployeeInfo.setEmployeeUid(request.getUid());
		nonEmployeeInfo.setEmployeeType(ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode());
		nonEmployeeInfo.setName(request.getName());
		if(StringUtils.isNotBlank(request.getGivenname()) && StringUtils.isNotBlank(request.getSurname())){
			nonEmployeeInfo.setFirstEnName(request.getGivenname());
			nonEmployeeInfo.setLastEnName(request.getSurname());
		}
		nonEmployeeInfo.setNationality(request.getNationality());
		nonEmployeeInfo.setGender(request.getGender());
		nonEmployeeInfo.setEmail(request.getMail());

		//处理电话号码
		MobilePhoneVo tel = request.getTel();
		if (tel != null) {
			String countryCode = tel.getCountryCode();
			String value = tel.getValue();
			if (StringUtils.isNotBlank(countryCode) && StringUtils.isNotBlank(value)) {
				String mobilePhone = countryCode + " " + value;
				nonEmployeeInfo.setMobilePhone(mobilePhone);
			}
		}

		//处理生日
		PassengerVo.Birth birth = request.getBirthday();
		if (birth != null) {
			String birthValue = birth.getValue();
			if (org.apache.commons.lang3.StringUtils.isNotBlank(birthValue)) {
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					Date parse = sf.parse(birthValue);
					nonEmployeeInfo.setBirthday(parse);
				} catch (ParseException e) {
					log.error("生日格式转换失败");
				}
			}
		}

		//处理新姓名信息
		NameInfoBo nameInfo = new NameInfoBo();
		nameInfo.setFullName(request.getName());
		nameInfo.setSurname(request.getSurname());
		nameInfo.setGivenname(request.getGivenname());
		nameInfo.setNationality(request.getNationality());
		String nameInfoString = JsonUtils.toJsonString(nameInfo);
		if(StrUtils.checkNameInfo(nameInfo)){
			nonEmployeeInfo.setNameInfo(nameInfoString);
		}
		organizationNonEmployeeInfoService.save(nonEmployeeInfo);

		// 2.保存证件信息
		if (Objects.nonNull(cardVo)) {
			MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
			mbOrgUserIdcard.setNonEmployeeId(nonEmployeeInfo.getId());
			mbOrgUserIdcard.setCardType(cardVo.getType());
			mbOrgUserIdcard.setCardNo(cardVo.getValue());
			mbOrgUserIdcard.setTimeLimit(cardVo.getValidity());
			mbOrgUserIdcard.setPlaceOfIssue(cardVo.getPlaceOfIssue());
			mbOrgUserIdcard.setDeleteTime(new Date(0));
			orgUserIdCardService.create(mbOrgUserIdcard);
		}

		// 3.保存新鲜度表信息
		MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
		mbFreshPassenger.setNonEmployeeUid(nonEmployeeInfo.getId());
		mbFreshPassenger.setCreateUid(request.getUid());
		mbFreshPassenger.setName(request.getName());
		if (StringUtils.isNotBlank(request.getSurname()) && StringUtils.isNotBlank(request.getGivenname())) {
			mbFreshPassenger.setEnName(request.getSurname() + "/" + request.getGivenname());
		}
		mbFreshPassenger.setValid(false);
		freshPassengerService.save(mbFreshPassenger);

        // 4.根据标识保存常旅客信息
        if (Objects.nonNull(request.getRelationFlag()) && request.getRelationFlag()){
            MbFreshPassengerRelation freshPassengerRelation = new MbFreshPassengerRelation();
            Date date = new Date();
            freshPassengerRelation.setDatachangeCreatetime(date);
            freshPassengerRelation.setDatachangeLasttime(date);
            freshPassengerRelation.setIsDeleted(false);
            freshPassengerRelation.setUid(request.getUid());
            freshPassengerRelation.setFreshTime(date);
            freshPassengerRelation.setEmployeeFlag(0);
            freshPassengerRelation.setFreshUid(nonEmployeeInfo.getId().toString());
            mbFreshPassengerRelationMapper.insertSelective(freshPassengerRelation);
        }

        String id = "id_" + nonEmployeeInfo.getId() + "_type_" + ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode();
        SavePassengerResponse response = new SavePassengerResponse();
        response.setNoEmployeeId(nonEmployeeInfo.getId().toString());
        response.setUniqueKey(id);
        response.setEmployeeType(ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode());
        return response;
	}

    public Boolean monitorPassengerName(MonitorPassengerNameRequest request){
        Date startTime = getStartTime(request);
        Date endTime = getEndTime(request);
        // 巡检员工信息表
        Example employeeExample = new Example(MbOrgEmployeeInfo.class);
        employeeExample.createCriteria().andBetween("dataChangeLastTime", startTime, endTime).andEqualTo("deleteTime", new Date(0));
        List<MbOrgEmployeeInfo> employeeInfoList = mbOrgEmployeeMapper.selectByExample(employeeExample);
        List<MbOrgEmployeeInfo> needWarnEmployeeInfoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(employeeInfoList)){
            needWarnEmployeeInfoList = employeeInfoList.stream().filter(this::checkEmployeeUnValidName).collect(Collectors.toList());
        }

        // 巡检非员工信息表
        Example nonEmployeeExample = new Example(MbOrgNonEmployeeInfo.class);
        nonEmployeeExample.createCriteria().andBetween("datachangeLasttime", startTime, endTime).andEqualTo("isDeleted", "0");
        List<MbOrgNonEmployeeInfo> nonEmployeeInfoList = mbOrgNonEmployeeMapper.selectByExample(nonEmployeeExample);
        List<MbOrgNonEmployeeInfo> needWarnNonEmployeeInfoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(nonEmployeeInfoList)){
            needWarnNonEmployeeInfoList = nonEmployeeInfoList.stream().filter(this::checkNonEmployeeUnValidName).collect(Collectors.toList());
        }

        // 记录需告警的数据
        ArrayList<MbPassportWarnInfo> passportWarnInfoList = new ArrayList<>();
        needWarnEmployeeInfoList.forEach(e ->{
            passportWarnInfoList.add(passportWarnConvert(e.getUid(), e.getEmployeeType()));
        });
        needWarnNonEmployeeInfoList.forEach(e ->{
            passportWarnInfoList.add(passportWarnConvert(e.getId().toString(), 2));
        });

        if (CollectionUtils.isEmpty(passportWarnInfoList)){
            return true;
        }
        //告警数据落库
        int counts = mbPassportWarnInfoMapper.insertList(passportWarnInfoList);
        return counts > 0;
    }

    private MbPassportWarnInfo passportWarnConvert(String uid, Integer employeeType) {
        MbPassportWarnInfo info = new MbPassportWarnInfo();
        info.setUid(uid);
        info.setEmployeeType(employeeType);
        info.setWarnType("NAME");
        info.setDatachangeCreatetime(new Date());
        info.setDatachangeLasttime(new Date());
        return info;
    }

    private Boolean checkEmployeeUnValidName(MbOrgEmployeeInfo info){
        return checkUnValidName(info.getFirstEnName(), info.getLastEnName(), info.getNameInfo());
    }

    private Boolean checkNonEmployeeUnValidName(MbOrgNonEmployeeInfo info){
        return checkUnValidName(info.getFirstEnName(), info.getLastEnName(), info.getNameInfo());
    }

    private Boolean checkUnValidName(String firstEnName, String lastEnName, String nameInfo){
        log.info("当前校验的信息为, firstEnName:{}, lastEnName:{}, nameInfo:{}", firstEnName, lastEnName, nameInfo);
        NameInfoBo nameInfoBo = null;
        // nameInfo格式错误的数据
        try {
            nameInfoBo = JsonUtils.parse(nameInfo, NameInfoBo.class);
            log.info("转换后的nameInfoBo:{}", JsonUtils.toJsonString(nameInfo));
        }catch (Exception e){
            log.error("NameInfo JSON转换失败!");
            return true;
        }
        // surName,givenName,fullName都为空的数据
        if (StringUtils.isBlank(nameInfoBo.getSurname()) && StringUtils.isBlank(nameInfoBo.getGivenname()) && StringUtils.isBlank(nameInfoBo.getFullName())){
            return true;
        }
        // surName与givenName一个为空一个不为空的数据
        if ((StringUtils.isBlank(nameInfoBo.getSurname()) && StringUtils.isNotBlank(nameInfoBo.getGivenname())) || (StringUtils.isBlank(nameInfoBo.getGivenname()) && StringUtils.isNotBlank(nameInfoBo.getSurname()))){
            return true;
        }
        // surName与lastEnName不相等
        if (StringUtils.isNotBlank(nameInfoBo.getSurname()) && StringUtils.isNotBlank(lastEnName) && !StringUtils.equals(nameInfoBo.getSurname(), lastEnName, false)){
            return true;
        }
        // givenName与firstEnName不相等
        if (StringUtils.isNotBlank(nameInfoBo.getGivenname()) && StringUtils.isNotBlank(firstEnName) && !StringUtils.equals(nameInfoBo.getGivenname(), firstEnName, false)){
            return true;
        }
        return false;
    }

    private Date getStartTime(MonitorPassengerNameRequest request){
        if (Objects.nonNull(request.getStartTime())){
            return request.getStartTime();
        }
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTime();
    }

    private Date getEndTime(MonitorPassengerNameRequest request){
        return Objects.nonNull(request.getEndTime()) ? request.getEndTime() : new Date();
    }

    public AddOrUpdatePassengerResponse addOrUpdatePassenger(AddOrUpdatePassengerRequest request, BaseUserInfo baseUserInfo){
	    // 如果新增和保存集合都为空，直接返回
	    if (CollectionUtils.isEmpty(request.getNeedAddPassengerList()) && CollectionUtils.isEmpty(request.getNeedUpdatePassengerList())) {
            return null;
        }

	    // 参数校验
        checkParam(request);

        Map<String, List<PassengerModifyInfo>> employeeMap = new HashMap<>();
        Map<String, List<PassengerModifyInfo>> nonEmployeeMap = new HashMap<>();

        // 新增集合一定是外部人员
        if (CollectionUtils.isNotEmpty(request.getNeedAddPassengerList())){
            nonEmployeeMap.put(ADD, request.getNeedAddPassengerList());
        }

        // 更新集合根据人员类型区分
        if (CollectionUtils.isNotEmpty(request.getNeedUpdatePassengerList())){
            request.getNeedUpdatePassengerList().forEach(e ->{
                if (ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode().equals(e.getEmployeeType())){
                    if (Objects.isNull(nonEmployeeMap.get(UPDATE))){
                        nonEmployeeMap.put(UPDATE, CollectionUtils.newArrayList(e));
                    } else {
                        nonEmployeeMap.get(UPDATE).add(e);
                    }
                } else {
                    if (Objects.isNull(employeeMap.get(UPDATE))){
                        employeeMap.put(UPDATE, CollectionUtils.newArrayList(e));
                    } else {
                        employeeMap.get(UPDATE).add(e);
                    }
                }
            });
        }
        log.info("需新增/更新的员工集合为:{}, 非员工集合为:{}", JsonUtils.toJsonString(employeeMap), JsonUtils.toJsonString(nonEmployeeMap));

        // 新增或更新人员信息表
        addOrUpdatePassengerInfo(employeeMap, nonEmployeeMap, baseUserInfo);

        // 新增或更新新鲜度信息
        addOrUpdateFreshInfo(employeeMap, nonEmployeeMap, baseUserInfo);

        // 新增或更新证件信息
        addOrUpdateCardInfo(employeeMap, nonEmployeeMap);

        // 组装结果并返回
        return addOrUpdatePassengerResponseConvert(request, nonEmployeeMap);
    }

    private AddOrUpdatePassengerResponse addOrUpdatePassengerResponseConvert(AddOrUpdatePassengerRequest request, Map<String, List<PassengerModifyInfo>> nonEmployeeMap) {
        AddOrUpdatePassengerResponse response = new AddOrUpdatePassengerResponse();
        ArrayList<PassengerInfo> added = new ArrayList<>();
        ArrayList<PassengerInfo> updated = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(request.getNeedAddPassengerList())){
            request.getNeedAddPassengerList().forEach(e ->{
                added.add(passengerResponseConvert(e));
            });
        }
        if (CollectionUtils.isNotEmpty(request.getNeedUpdatePassengerList())){
            request.getNeedUpdatePassengerList().forEach(e ->{
                updated.add(passengerResponseConvert(e));
            });
        }
        response.setAddedPassengerList(added);
        response.setUpdatedPassengerList(updated);
        return response;
    }

    private PassengerInfo passengerResponseConvert(PassengerModifyInfo passengerModifyInfo) {
        PassengerInfo info = new PassengerInfo();
        info.setEmployeeType(passengerModifyInfo.getEmployeeType());
        info.setIdentifyTag(passengerModifyInfo.getIdentifyTag());
        info.setNoEmployeeId(passengerModifyInfo.getNoEmployeeId());
        info.setUid(passengerModifyInfo.getUid());
        return info;
    }

    private void addOrUpdateCardInfo(Map<String, List<PassengerModifyInfo>> employeeMap, Map<String, List<PassengerModifyInfo>> nonEmployeeMap) {
        ArrayList<MbOrgUserIdcard> needAddCardList = new ArrayList<>();
        ArrayList<MbOrgUserIdcard> needUpdateCardList = new ArrayList<>();

        List<MbOrgUserIdcard> existedCardList = queryExistedCard(employeeMap, nonEmployeeMap);
        List<MbOrgUserIdcard> employeeCardList = existedCardList.stream().filter(e -> StringUtils.isNotBlank(e.getEmployeeUid())).collect(Collectors.toList());
        List<MbOrgUserIdcard> nonEmployeeCardList = existedCardList.stream().filter(e -> Objects.nonNull(e.getNonEmployeeId())).collect(Collectors.toList());

        Map<String, List<MbOrgUserIdcard>> employeeCardMap = employeeCardMapConvert(employeeCardList);
        Map<String, List<MbOrgUserIdcard>> nonEmployeeCardMap = nonEmployeeCardMapConvert(nonEmployeeCardList);

        if (CollectionUtils.isNotEmpty(nonEmployeeMap.get(ADD))){
            List<PassengerModifyInfo> containCardPassengerList = nonEmployeeMap.get(ADD).stream().filter(e -> CollectionUtils.isNotEmpty(e.getCard())).collect(Collectors.toList());
            containCardPassengerList.forEach(e ->{
                e.getCard().forEach(k ->{
                    needAddCardList.add(nonEmployeeCardInfoConvert(k, e, ADD));
                });
            });
        }

        if (CollectionUtils.isNotEmpty(nonEmployeeMap.get(UPDATE))){
            List<PassengerModifyInfo> containCardPassengerList = nonEmployeeMap.get(UPDATE).stream().filter(e -> CollectionUtils.isNotEmpty(e.getCard())).collect(Collectors.toList());
            containCardPassengerList.forEach(e ->{
                e.getCard().forEach(k ->{
                    MbOrgUserIdcard existCard = findExistCard(e.getNoEmployeeId(), k, nonEmployeeCardMap);
                    //  如果证件已存在，则加入更新列表
                    if (Objects.nonNull(existCard)){
                        needUpdateCardList.add(idCardBaseConvert(existCard, k, UPDATE));
                    } else {
                        // 不存在则加入新增列表
                        needAddCardList.add(nonEmployeeCardInfoConvert(k, e, ADD));
                    }
                });
            });
        }

        if (CollectionUtils.isNotEmpty(employeeMap.get(UPDATE))){
            List<PassengerModifyInfo> containCardPassengerList = employeeMap.get(UPDATE).stream().filter(e -> CollectionUtils.isNotEmpty(e.getCard())).collect(Collectors.toList());
            containCardPassengerList.forEach(e ->{
                e.getCard().forEach(k ->{
                    MbOrgUserIdcard existCard = findExistCard(e.getUid(), k, employeeCardMap);
                    // 如果证件已存在，则加入更新列表
                    if (Objects.nonNull(existCard)){
                        needUpdateCardList.add(idCardBaseConvert(existCard, k, UPDATE));
                    } else {
                        // 不存在则加入新增列表
                        needAddCardList.add(employeeCardInfoConvert(k, e, ADD));
                    }
                });
            });
        }

        log.info("需要新增的证件集合为:{}, 需要更新的证件集合为:{}", JsonUtils.toJsonString(needAddCardList), JsonUtils.toJsonString(needUpdateCardList));

        // 处理需新增的证件
        if (CollectionUtils.isNotEmpty(needAddCardList)){
            int idCardInsert = mbOrgUserIdcardMapper.insertList(needAddCardList);
            if (idCardInsert <= 0){
                log.error("mbOrgUserIdCard insert failed!");
            }
        }

        // 处理需更新的证件
        if (CollectionUtils.isNotEmpty(needUpdateCardList)){
            int idCardUpdate = mbOrgUserIdcardMapper.updateBatchSelective(needUpdateCardList);
            if (idCardUpdate <= 0){
                log.error("mbOrgUserIdCard update failed!");
            }
        }
    }

    private MbOrgUserIdcard employeeCardInfoConvert(CardVo cardVo, PassengerModifyInfo passengerModifyInfo, String status) {
        MbOrgUserIdcard card = new MbOrgUserIdcard();
        card.setEmployeeUid(passengerModifyInfo.getUid());
        return idCardBaseConvert(card, cardVo, status);
    }

    private MbOrgUserIdcard nonEmployeeCardInfoConvert(CardVo cardVo, PassengerModifyInfo passengerModifyInfo, String status) {
        MbOrgUserIdcard card = new MbOrgUserIdcard();
        card.setNonEmployeeId(Long.valueOf(passengerModifyInfo.getNoEmployeeId()));
        return idCardBaseConvert(card, cardVo, status);
    }

    private MbOrgUserIdcard idCardBaseConvert(MbOrgUserIdcard card, CardVo cardVo, String status){
        card.setCardType(cardVo.getType());
        card.setCardNo(cardVo.getValue());
        card.setTimeLimit(cardVo.getValidity());
        card.setPlaceOfIssue(cardVo.getPlaceOfIssue());
        card.setDeleteTime(new Date(0));
        if (ADD.equals(status)){
            card.setDatachangeCreatetime(new Date());
            card.setDatachangeLasttime(new Date());
        }
        return card;
    }

    // 查找已存在的证件类型
    private MbOrgUserIdcard findExistCard(String key, CardVo card, Map<String, List<MbOrgUserIdcard>> map) {
        if (CollectionUtils.isEmpty(map.get(key))){
            return null;
        }
        return map.get(key).stream().filter(e -> e.getCardType().equals(card.getType())).findFirst().orElse(null);
    }

    private Map<String, List<MbOrgUserIdcard>> nonEmployeeCardMapConvert(List<MbOrgUserIdcard> nonEmployeeCardList) {
        HashMap<String, List<MbOrgUserIdcard>> map = new HashMap<>();
        if (CollectionUtils.isEmpty(nonEmployeeCardList)){
            return map;
        }
        nonEmployeeCardList.forEach(e ->{
            if (Objects.isNull(map.get(e.getNonEmployeeId().toString()))){
                map.put(e.getNonEmployeeId().toString(), CollectionUtils.newArrayList(e));
            } else {
                map.get(e.getNonEmployeeId().toString()).add(e);
            }
        });
        return map;
    }

    private Map<String, List<MbOrgUserIdcard>> employeeCardMapConvert(List<MbOrgUserIdcard> employeeCardList) {
        HashMap<String, List<MbOrgUserIdcard>> map = new HashMap<>();
        if (CollectionUtils.isEmpty(employeeCardList)){
            return map;
        }
        employeeCardList.forEach(e ->{
            if (Objects.isNull(map.get(e.getEmployeeUid()))){
                map.put(e.getEmployeeUid(), CollectionUtils.newArrayList(e));
            } else {
                map.get(e.getEmployeeUid()).add(e);
            }
        });
        return map;
    }

    private List<MbOrgUserIdcard> queryExistedCard(Map<String, List<PassengerModifyInfo>> employeeMap, Map<String, List<PassengerModifyInfo>> nonEmployeeMap) {
        ArrayList<String> uidList = new ArrayList<>();
        ArrayList<Long> nonEmployeeIdList = new ArrayList<>();

        if (Objects.nonNull(employeeMap.get(UPDATE))){
            employeeMap.get(UPDATE).forEach(e ->{
                uidList.add(e.getUid());
            });
        }

        if (Objects.nonNull(nonEmployeeMap.get(UPDATE))){
            nonEmployeeMap.get(UPDATE).forEach(e ->{
                nonEmployeeIdList.add(Long.valueOf(e.getNoEmployeeId()));
            });
        }
        Example example = new Example(MbOrgUserIdcard.class);
        Example.Criteria criteria = example.createCriteria();
        if (CollectionUtils.isNotEmpty(uidList)){
            criteria.orIn("employeeUid", uidList);
        }
        if (CollectionUtils.isNotEmpty(nonEmployeeIdList)){
            criteria.orIn("nonEmployeeId", nonEmployeeIdList);
        }
        criteria.andEqualTo("deleteTime", new Date(0));
        return mbOrgUserIdcardMapper.selectByExample(example);
    }

    private void addOrUpdateFreshInfo(Map<String, List<PassengerModifyInfo>> employeeMap, Map<String, List<PassengerModifyInfo>> nonEmployeeMap, BaseUserInfo baseUserInfo) {
        ArrayList<MbFreshPassenger> needAddFreshInfoList = new ArrayList<>();
        ArrayList<MbFreshPassenger> needUpdateFreshInfoList = new ArrayList<>();

        // 处理需新增的新鲜度信息
        if (CollectionUtils.isNotEmpty(nonEmployeeMap.get(ADD))){
            nonEmployeeMap.get(ADD).forEach(e ->{
                needAddFreshInfoList.add(nonEmployeeFreshInfoConvert(e, baseUserInfo, ADD));
            });
        }

        // 处理需更新的新鲜度信息
        if (CollectionUtils.isNotEmpty(nonEmployeeMap.get(UPDATE))){
            nonEmployeeMap.get(UPDATE).forEach(e ->{
                needUpdateFreshInfoList.add(nonEmployeeFreshInfoConvert(e, baseUserInfo, UPDATE));
            });
        }

        if (CollectionUtils.isNotEmpty(employeeMap.get(UPDATE))){
            employeeMap.get(UPDATE).forEach(e ->{
                needUpdateFreshInfoList.add(employeeFreshInfoConvert(e));
            });
        }

        log.info("需新增的新鲜度数据为:{},需更新的新鲜度数据为:{}", JsonUtils.toJsonString(needAddFreshInfoList), JsonUtils.toJsonString(needUpdateFreshInfoList));

        // 处理新增数据
        if (CollectionUtils.isNotEmpty(needAddFreshInfoList)) {
            int insertFreshList = mbFreshPassengerMapper.insertList(needAddFreshInfoList);
            if (insertFreshList <= 0){
                log.error("mbFreshPassenger batch insert failed!");
            }
        }

        // 处理更新数据
        if (CollectionUtils.isNotEmpty(needUpdateFreshInfoList)){
            int updateFreshList = mbFreshPassengerMapper.updateBatchSelective(needUpdateFreshInfoList);
            if (updateFreshList <= 0){
                log.error("mbFreshPassenger batch insert failed!");
            }
        }
    }

    private MbFreshPassenger employeeFreshInfoConvert(PassengerModifyInfo passengerModifyInfo) {
        MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
        mbFreshPassenger.setEmployeeUid(passengerModifyInfo.getUid());
        mbFreshPassenger.setName(StringUtils.isBlank(passengerModifyInfo.getFullName()) ? passengerModifyInfo.getFullName() : passengerModifyInfo.getName());
        mbFreshPassenger.setEnName(freshEnNameConvert(passengerModifyInfo));
        mbFreshPassenger.setValid(false);
        return mbFreshPassenger;
    }

    private MbFreshPassenger nonEmployeeFreshInfoConvert(PassengerModifyInfo passengerModifyInfo, BaseUserInfo baseUserInfo, String status) {
	    MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
        mbFreshPassenger.setNonEmployeeUid(Long.valueOf(passengerModifyInfo.getNoEmployeeId()));
        mbFreshPassenger.setCreateUid(baseUserInfo.getUid());
        mbFreshPassenger.setName(StringUtils.isBlank(passengerModifyInfo.getFullName()) ? passengerModifyInfo.getFullName() : passengerModifyInfo.getName());
        mbFreshPassenger.setEnName(freshEnNameConvert(passengerModifyInfo));
        mbFreshPassenger.setValid(false);
        if (ADD.equals(status)){
            mbFreshPassenger.setDatachangeCreatetime(new Date());
            mbFreshPassenger.setDatachangeLasttime(new Date());
            mbFreshPassenger.setFreshTime(new Date());
            mbFreshPassenger.setIsDeleted(false);
        }
        return mbFreshPassenger;
    }

    private String freshEnNameConvert(PassengerModifyInfo passengerModifyInfo){
        if (StringUtils.isNotBlank(passengerModifyInfo.getSurname()) & StringUtils.isNotBlank(passengerModifyInfo.getGivenname())){
            return passengerModifyInfo.getSurname() + "/" + passengerModifyInfo.getGivenname();
        } else {
            return passengerModifyInfo.getLastEnName() + "/" + passengerModifyInfo.getFirstEnName();
        }
    }

    private void addOrUpdatePassengerInfo(Map<String, List<PassengerModifyInfo>> employeeMap, Map<String, List<PassengerModifyInfo>> nonEmployeeMap, BaseUserInfo baseUserInfo) {
	    // 需更新的员工集合
	    List<MbOrgEmployeeInfo> updateEmployeeList = employeeListConvert(employeeMap.get(UPDATE));
	    // 需新增的非员工集合
	    List<MbOrgNonEmployeeInfo> addNonEmployeeList = nonEmployeeListConvert(nonEmployeeMap.get(ADD), baseUserInfo, ADD);
	    // 需更新的非员工集合
	    List<MbOrgNonEmployeeInfo> updateNonEmployeeList = nonEmployeeListConvert(nonEmployeeMap.get(UPDATE), baseUserInfo, UPDATE);
	    log.info("需更新的员工集合为:{}, 非员工集合为:{},需添加的非员工集合为:{}", JsonUtils.toJsonString(updateEmployeeList), JsonUtils.toJsonString(updateNonEmployeeList), JsonUtils.toJsonString(addNonEmployeeList));

	    // 更新员工
	    if (CollectionUtils.isNotEmpty(updateEmployeeList)){
            int updateEmployee = mbOrgEmployeeMapper.updateBatchSelective(updateEmployeeList);
            if (updateEmployee <= 0){
                log.error("updateEmployeeList failed!");
            }
        }

	    // 更新非员工
	    if (CollectionUtils.isNotEmpty(updateNonEmployeeList)){
            int updateNonEmployee = mbOrgNonEmployeeMapper.updateBatchSelective(updateNonEmployeeList);
            if (updateNonEmployee <= 0){
                log.error("updateNonEmployeeList failed!");
            }
        }

	    //新增非员工
        if (CollectionUtils.isNotEmpty(addNonEmployeeList)){
            int addNonEmployee = mbOrgNonEmployeeMapper.insertList(addNonEmployeeList);;
            if (addNonEmployee <= 0){
                log.error("addNonEmployeeList failed!");
            }
            // 将主键回填
            nonEmployeeMap.get(ADD).forEach(e ->{
                MbOrgNonEmployeeInfo mbOrgNonEmployeeInfo = addNonEmployeeList.stream().filter(k -> k.getIdentifyTag().equals(e.getIdentifyTag())).findFirst().orElse(null);
                if (Objects.nonNull(mbOrgNonEmployeeInfo)) {
                    e.setNoEmployeeId(mbOrgNonEmployeeInfo.getId().toString());
                }
            });
        }
    }

    private List<MbOrgNonEmployeeInfo> nonEmployeeListConvert(List<PassengerModifyInfo> passengerModifyInfoList, BaseUserInfo baseUserInfo, String status) {
	    if (CollectionUtils.isEmpty(passengerModifyInfoList)){
	        return null;
        }
        ArrayList<MbOrgNonEmployeeInfo> list = new ArrayList<>();
        passengerModifyInfoList.forEach(e ->{
            list.add(nonEmployeeConvert(e, baseUserInfo, status));
        });
        return list;
    }

    private MbOrgNonEmployeeInfo nonEmployeeConvert(PassengerModifyInfo passengerModifyInfo, BaseUserInfo baseUserInfo, String status) {
        MbOrgNonEmployeeInfo info = new MbOrgNonEmployeeInfo();
        info.setEmployeeUid(baseUserInfo.getUid());
        if (StringUtils.isBlank(passengerModifyInfo.getFullName())){
            passengerModifyInfo.setFullName(passengerModifyInfo.getName());
        }
        info.setName(passengerModifyInfo.getFullName());
        info.setValid(VALID);
        info.setEmail(passengerModifyInfo.getMail());
        if (Objects.nonNull(passengerModifyInfo.getTel())){
            info.setMobilePhone(passengerModifyInfo.getTel().getValue());
        }
        info.setGender(passengerModifyInfo.getGender());
        if (Objects.nonNull(passengerModifyInfo.getBirth())){
            Date birthday = birthDayConvert(passengerModifyInfo.getBirth());
            if (Objects.nonNull(birthday)){
                info.setBirthday(birthday);
            }
        }
        info.setFirstEnName(passengerModifyInfo.getFirstEnName());
        info.setLastEnName(passengerModifyInfo.getLastEnName());
        info.setNationality(passengerModifyInfo.getNationality());
        info.setEmployeeType(passengerModifyInfo.getEmployeeType());
        NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(passengerModifyInfo),NameInfoBo.class);
        if(StrUtils.checkNameInfo(nameInfoBo)){
            info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
        }
        info.setIdentifyTag(passengerModifyInfo.getIdentifyTag());
        if (ADD.equals(status)) {
            info.setDatachangeLasttime(new Date());
            info.setDatachangeCreatetime(new Date());
        } else {
            info.setId(Long.valueOf(passengerModifyInfo.getNoEmployeeId()));
        }
        return info;
    }

    private List<MbOrgEmployeeInfo> employeeListConvert(List<PassengerModifyInfo> passengerModifyInfoList) {
	    if (CollectionUtils.isEmpty(passengerModifyInfoList)){
	        return null;
        }
        ArrayList<MbOrgEmployeeInfo> list = new ArrayList<>();
        passengerModifyInfoList.forEach(e ->{
            list.add(employeeConvert(e));
        });
        return list;
    }

    private MbOrgEmployeeInfo employeeConvert(PassengerModifyInfo passengerModifyInfo) {
        MbOrgEmployeeInfo info = new MbOrgEmployeeInfo();
        info.setUid(passengerModifyInfo.getUid());
        // 兼容fullName与name，优先使用fullName
        if (StringUtils.isBlank(passengerModifyInfo.getFullName())){
            passengerModifyInfo.setFullName(passengerModifyInfo.getName());
        }
        info.setName(passengerModifyInfo.getFullName());
        info.setValid(VALID);
        if (Objects.nonNull(passengerModifyInfo.getTel())){
            info.setMobilePhone(passengerModifyInfo.getTel().getValue());
            info.setAreaCode(passengerModifyInfo.getTel().getCountryCode());
        }
        info.setEmail(passengerModifyInfo.getMail());
        info.setGender(passengerModifyInfo.getGender());
        if (Objects.nonNull(passengerModifyInfo.getBirth())){
            Date birthday = birthDayConvert(passengerModifyInfo.getBirth());
            if (Objects.nonNull(birthday)){
                info.setBirthday(birthday);
            }
        }
        info.setFirstEnName(passengerModifyInfo.getFirstEnName());
        info.setLastEnName(passengerModifyInfo.getLastEnName());
        info.setNationality(passengerModifyInfo.getNationality());
        info.setEmployeeType(passengerModifyInfo.getEmployeeType());
        NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(passengerModifyInfo),NameInfoBo.class);
        if(StrUtils.checkNameInfo(nameInfoBo)){
            info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
        }
        return info;
    }

    private Date birthDayConvert(PassengerVo.Birth birth) {
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
        try{
            return sdf.parse(birth.getValue());
        } catch (Exception e){
            log.error("birthday:{}转换失败", JsonUtils.toJsonString(birth));
        }
        return null;
    }

    private void checkParam(AddOrUpdatePassengerRequest request) {
        // 校验人员类型是否符合规范
	    if (CollectionUtils.isNotEmpty(request.getNeedAddPassengerList())){
	        request.getNeedAddPassengerList().forEach(e ->{
                if (Objects.isNull(e.getEmployeeType()) || Objects.isNull(ApplyTripEmployeeEnum.getNameByCode(e.getEmployeeType()))){
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_ERROR);
                }
            });
        }

	    if (CollectionUtils.isNotEmpty(request.getNeedUpdatePassengerList())){
	        request.getNeedUpdatePassengerList().forEach(e ->{
	            if (Objects.isNull(e.getEmployeeType()) || Objects.isNull(ApplyTripEmployeeEnum.getNameByCode(e.getEmployeeType()))){
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_ERROR);
                }
            });
        }
    }

    public Boolean updateFreshEnNameBatch(){
        IPage<Object> initPage = PageContext.startPage(1, CommonConst.PAGE_SIZE_300);
        List<MbFreshPassenger> mbFreshPassengerList = mbFreshPassengerMapper.listAllValidFreshPassengers();
        for (int currentPage = 1; currentPage <= initPage.getPages(); currentPage ++){
            PageContext.startPage(currentPage, CommonConst.PAGE_SIZE_300);
            List<MbFreshPassenger> freshPassengerList = mbFreshPassengerMapper.listAllValidFreshPassengers();
            updateEnName(freshPassengerList);
        }
        return true;
    }

    private void updateEnName(List<MbFreshPassenger> freshPassengerList){
	    if (CollectionUtils.isEmpty(freshPassengerList)){
	        return;
        }
	    log.info("当前批次处理的新鲜度数据为:{}", JsonUtils.toJsonString(freshPassengerList));
        List<MbFreshPassenger> employeeList = freshPassengerList.stream().filter(e -> StringUtils.isNotBlank(e.getEmployeeUid())).collect(Collectors.toList());
        List<MbFreshPassenger> nonEmployeeList = freshPassengerList.stream().filter(e -> Objects.nonNull(e.getNonEmployeeUid())).collect(Collectors.toList());
        log.info("当前批次处理的员工新鲜度集合为:{}, 非员工新鲜度集合为:{}", JsonUtils.toJsonString(employeeList), JsonUtils.toJsonString(nonEmployeeList));
        List<String> uidList = employeeList.stream().map(MbFreshPassenger::getEmployeeUid).collect(Collectors.toList());
        List<Long> nonEmployeeIdList = nonEmployeeList.stream().map(MbFreshPassenger::getNonEmployeeUid).collect(Collectors.toList());

        List<MbOrgEmployeeInfo> employeeInfoList = new ArrayList<>();
        List<MbOrgNonEmployeeInfo> nonEmployeeInfoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(uidList)) {
            employeeInfoList = mbOrgEmployeeMapper.listByUids(uidList);
        }
        if (CollectionUtils.isNotEmpty(nonEmployeeIdList)) {
            nonEmployeeInfoList = mbOrgNonEmployeeMapper.listByIds(nonEmployeeIdList);
        }
        List<MbOrgEmployeeInfo> finalEmployeeInfoList = employeeInfoList;
        List<MbOrgNonEmployeeInfo> finalNonEmployeeInfoList = nonEmployeeInfoList;
        freshPassengerList.forEach(e ->{
            String enName = enNameConvert(e, finalEmployeeInfoList, finalNonEmployeeInfoList);
            if (StringUtils.isNotBlank(enName)){
                e.setEnName(enName);
            }
        });
        List<MbFreshPassenger> updateList = freshPassengerList.stream().filter(e -> StringUtils.isNotBlank(e.getEnName())).collect(Collectors.toList());
        log.info("当前批次更新的数据集合为:{}", JsonUtils.toJsonString(updateList));
        if (CollectionUtils.isNotEmpty(updateList)) {
            int update = mbFreshPassengerMapper.updateEnNameBatch(updateList);
            log.info("当前批次更新数据量为:{}", update);
        }
    }

    private String enNameConvert(MbFreshPassenger freshPassenger, List<MbOrgEmployeeInfo> employeeInfoList, List<MbOrgNonEmployeeInfo> nonEmployeeInfoList) {
	    // 员工
	    if (Objects.nonNull(freshPassenger.getEmployeeUid())){
            MbOrgEmployeeInfo info = employeeInfoList.stream().filter(e -> freshPassenger.getEmployeeUid().equals(e.getUid())).findFirst().orElse(null);
            if (Objects.nonNull(info) && StringUtils.isNotBlank(info.getFirstEnName()) && StringUtils.isNotBlank(info.getLastEnName())) {
                return enNameCombine(info.getFirstEnName(), info.getLastEnName());
            }
        } else {
	        // 非员工
            MbOrgNonEmployeeInfo info = nonEmployeeInfoList.stream().filter(e -> freshPassenger.getNonEmployeeUid().equals(e.getId())).findFirst().orElse(null);
            if (Objects.nonNull(info) && StringUtils.isNotBlank(info.getFirstEnName()) && StringUtils.isNotBlank(info.getLastEnName())){
                return enNameCombine(info.getFirstEnName(), info.getLastEnName());
            }
        }
	    return null;
    }

    private String enNameCombine(String firstEnName, String lastEnName) {
	    return firstEnName + "/" + lastEnName;
    }

    public CheckPassengerRequest checkPassengerNew(CheckPassengerRequest request, BaseUserInfo baseUserInfo) {
	    if (CollectionUtils.isEmpty(request.getPassengerVos())){
	        log.error("当前请求不包含出行人数据");
	        return request;
        }
	    log.info("批量新增/保存出行人原始数据为:{}", JsonUtils.toJsonString(request));
	    fillEmployeeType(request);
        AddOrUpdatePassengerRequest addOrUpdatePassengerRequest = addOrUpdatePassengerRequestConvert(request);
        AddOrUpdatePassengerResponse addOrUpdatePassengerResponse = addOrUpdatePassenger(addOrUpdatePassengerRequest, baseUserInfo);
        if (Objects.isNull(addOrUpdatePassengerResponse) || CollectionUtils.isEmpty(addOrUpdatePassengerResponse.getAddedPassengerList())){
            return request;
        }
        request.getPassengerVos().forEach(e ->{
            // 新增的外部人员将noEmployeeId回填
            if (StringUtils.isNotBlank(e.getNoEmployeeId()) && startsWith(e.getNoEmployeeId(), ADD, true)){
                PassengerInfo passengerInfo = addOrUpdatePassengerResponse.getAddedPassengerList().stream().filter(k -> e.getNoEmployeeId().equals(k.getIdentifyTag())).findFirst().orElse(null);
                if (Objects.nonNull(passengerInfo)) {
                    e.setNoEmployeeId(passengerInfo.getNoEmployeeId());
                }
            }
        });
        log.info("批量新增/保存出行人回填noEmployeeId后数据为:{}", JsonUtils.toJsonString(request));
        return request;
    }

    private void fillEmployeeType(CheckPassengerRequest request) {
	    request.getPassengerVos().forEach(e ->{
	        if (Objects.isNull(e.getEmployeeType())){
	            e.setEmployeeType(StringUtils.isNotBlank(e.getNoEmployeeId()) ? ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode() : ApplyTripEmployeeEnum.EMPLOYEE.getCode());
            }
        });
    }

    private AddOrUpdatePassengerRequest addOrUpdatePassengerRequestConvert(CheckPassengerRequest request) {
        AddOrUpdatePassengerRequest passengerRequest = new AddOrUpdatePassengerRequest();
        List<PassengerVo> needAddList = request.getPassengerVos().stream().filter(e -> StringUtils.isNotBlank(e.getNoEmployeeId())).filter(e -> startsWith(e.getNoEmployeeId(), ADD, true)).collect(Collectors.toList());
        List<PassengerVo> needUpdateList = request.getPassengerVos().stream().filter(e -> !needAddList.contains(e)).collect(Collectors.toList());
        ArrayList<PassengerModifyInfo> addList = new ArrayList<>();
        ArrayList<PassengerModifyInfo> updateList = new ArrayList<>();
        needAddList.forEach(e ->{
            PassengerModifyInfo info = passengerModifyInfoConvert(e);
            info.setIdentifyTag(e.getNoEmployeeId());
            addList.add(info);
        });
        needUpdateList.forEach(e ->{
            PassengerModifyInfo info = passengerModifyInfoConvert(e);
            info.setUid(e.getUid());
            info.setNoEmployeeId(e.getNoEmployeeId());
            updateList.add(info);
        });
        passengerRequest.setNeedAddPassengerList(addList);
        passengerRequest.setNeedUpdatePassengerList(updateList);
        return passengerRequest;
    }

    private PassengerModifyInfo passengerModifyInfoConvert(PassengerVo passengerVo){
        PassengerModifyInfo info = new PassengerModifyInfo();
        info.setEmployeeType(passengerVo.getEmployeeType());
        info.setOrgId(passengerVo.getOrgId());
        info.setFullName(passengerVo.getFullName());
        info.setName(passengerVo.getName());
        info.setFullEnName(passengerVo.getFullEnName());
        info.setPassport(passengerVo.getPassport());
        info.setSurname(passengerVo.getSurname());
        info.setGivenname(passengerVo.getGivenname());
        if (Objects.nonNull(passengerVo.getTel())) {
            info.setTel(passengerVo.getTel());
        }
        if (CollectionUtils.isNotEmpty(passengerVo.getSource())) {
            info.setCard(passengerVo.getSource());
        }
        if (Objects.nonNull(passengerVo.getBirth())) {
            info.setBirth(passengerVo.getBirth());
        }
        info.setNationality(passengerVo.getNationality());
        info.setGender(passengerVo.getGender());
        info.setAge(passengerVo.getAge());
        info.setMail(passengerVo.getMail());
        return info;
    }

    public CheckPassengerResponse checkPassengerResponseConvert(CheckPassengerRequest request) {
        CheckPassengerResponse response = new CheckPassengerResponse();
        response.setUid(request.getUid());
        response.setPassengerVos(request.getPassengerVos());
        return response;
    }

	/**
	 * 删除外部人员信息
	 * @param request
	 * @return
	 */
	public Boolean deleteNonEmployeePassenger(DeletePassengerRequest request) {
		if(StringUtils.isEmpty(request.getNoEmployeeId())) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.BODY_NULL);
		}
		Long noEmployeeId = Long.valueOf(request.getNoEmployeeId());

		MbOrgNonEmployeeInfo nonEmployeeInfo = mbOrgNonEmployeeMapper.selectByNonEmployee(noEmployeeId);
		if (nonEmployeeInfo == null) {
			log.info("未查询到可删除外部出行人：{}", JsonUtils.toJsonString(request));
			throw new CorpBusinessException(OrganizationResponseCodeEnum.NON_EMPLOYEE_NULL);
		}
		if(!StringUtils.endsWithIgnoreCase(nonEmployeeInfo.getEmployeeUid(), request.getUid())) {
			log.info("外部出行人的创建员工不是当前用户：{}", JsonUtils.toJsonString(request));
			throw new CorpBusinessException(OrganizationResponseCodeEnum.NON_EMPLOYEE_NOT_USER);
		}
		// 删除外部出行人
        mbOrgNonEmployeeMapper.deleteByNonId(noEmployeeId);
		// 删除卡片信息
		mbOrgUserIdcardMapper.deleteByNonEmployeeUid(Long.valueOf(request.getNoEmployeeId()));
		// 删除关联关系
		mbFreshPassengerRelationMapper.deletedRelation(request.getUid(), request.getNoEmployeeId());
		// 删除人员新鲜度
		mbFreshPassengerMapper.deleteNonEmployee(noEmployeeId);

		return true;
	}

	public List<OrderResultPassengerResponse> getOrderResultByPassengers(OrderResultPassengerRequest request) {
		log.info("getOrderResultByPassengers request:{}", JsonUtils.toJsonString(request));
		if(request == null || CollectionUtils.isEmpty(request.getPassengerInfoList())
				|| StringUtils.isEmpty(request.getProductType())) {
			return null;
		}
		List<OrderResultPassengerInfo> passengerInfos = request.getPassengerInfoList().stream().filter(t->t.getEmployeeType()!=2).collect(Collectors.toList());
		List<OrderResultPassengerResponse> resultPassengerResponseList = new ArrayList<>();
		if (CollectionUtils.isEmpty(passengerInfos)) {
			return coverPassengerResponse(resultPassengerResponseList, request);
		}

		List<String> orgIdList = request.getPassengerInfoList().stream().map(OrderResultPassengerInfo::getOrgId).distinct().collect(Collectors.toList());
		if(CollectionUtils.isEmpty(orgIdList)) {
			log.info("用户机构ID为空");
			return null;
		}
		// 机构和公司对映关系
		Map<String, String> orgTypeMap = new HashMap<>();
		// 公司编码
		List<String> companyIdList = new ArrayList<>();
		orgIdList.stream().forEach(t->{
			MbOrgInfo orgInfo = organizationInfoService.findFirstCompany(t);
			if(orgInfo != null) {
				orgTypeMap.put(t, orgInfo.getOrgId());
				companyIdList.add(orgInfo.getOrgId());
			}
		});
		if(CollectionUtils.isEmpty(companyIdList)) {
			log.info("最底层公司ID为空");
			return null;
		}
		List<SupplierCompany> supplierCompanyList = mbSupplierCompanyMapper.queryOrderResultByCompanyList(companyIdList, request.getProductType());
		if (CollectionUtils.isEmpty(supplierCompanyList)) {
			return coverPassengerResponse(resultPassengerResponseList, request);
		}
		Map<String, SupplierCompany> orgMap = supplierCompanyList.stream().collect(Collectors.toMap(SupplierCompany::getCompanyCode,p->p));
		request.getPassengerInfoList().stream().forEach(t->{
			OrderResultPassengerResponse passengerResponse = new OrderResultPassengerResponse();
			passengerResponse.setUid(t.getUid());
			passengerResponse.setEmployeeType(t.getEmployeeType());
			if(t.getEmployeeType() != 2 && orgTypeMap.containsKey(t.getOrgId()) && orgMap.containsKey(orgTypeMap.get(t.getOrgId()))) {
				//查询到企业订购业务
				passengerResponse.setOrderResultFlag(true);
			} else {
				passengerResponse.setOrderResultFlag(false);
			}
			resultPassengerResponseList.add(passengerResponse);
		});
		log.info("getOrderResultByPassengers response:{}", JsonUtils.toJsonString(resultPassengerResponseList));
		return resultPassengerResponseList;
	}

	/**
	 * 全都未开启企业订购业务
	 * @param resultPassengerResponseList
	 * @param request
	 * @return
	 */
	private List<OrderResultPassengerResponse> coverPassengerResponse(List<OrderResultPassengerResponse> resultPassengerResponseList, OrderResultPassengerRequest request) {
		request.getPassengerInfoList().stream().forEach(t->{
			OrderResultPassengerResponse passengerResponse = new OrderResultPassengerResponse();
			passengerResponse.setUid(t.getUid());
			passengerResponse.setEmployeeType(t.getEmployeeType());
			passengerResponse.setOrderResultFlag(false);
			resultPassengerResponseList.add(passengerResponse);
		});
		return resultPassengerResponseList;
	}
}
